package cn.zptc.service.impl;

import cn.zptc.dao.FavoriteDao;
import cn.zptc.dao.LinkDao;
import cn.zptc.dao.impl.LinkDaoImpl;
import cn.zptc.entity.Favorite;
import cn.zptc.entity.FavoriteCategory;
import cn.zptc.service.FavoriteService;

import java.sql.SQLException;
import java.util.List;

public class FavoriteServiceImpl implements FavoriteService {
    private FavoriteDao favoriteDao;


    public FavoriteServiceImpl() {
    }

    public FavoriteServiceImpl(FavoriteDao favoriteDao) {
        this.favoriteDao = favoriteDao;
    }


    @Override
    public List<FavoriteCategory> getMyFavoriteCategorys(int userId) throws SQLException {
        List<FavoriteCategory> linkCategories= favoriteDao.selectMyFavoriteCategorys(userId);
        return linkCategories;
    }

    @Override
    public int addFavorite(Favorite favorite) throws SQLException {
        String linkUrl = favorite.getLinkUrl();
        //判断linkurl是否在数据库存在，如果存在，获取linkId,不存在的话，新增linkurl到数据库
        LinkDao linkDao = new LinkDaoImpl();
        int id = linkDao.selectLinkId(linkUrl);
        if (id==-1){
            id =linkDao.insert(linkUrl);
        }
        if (id==-1){
            throw  new RuntimeException("新增链接失败");
        }else {
            favorite.setLinkId(id);
            return favoriteDao.insert(favorite);
        }
    }

    /**
     * 获取我的收藏
     *
     * @param userId
     * @return
     */
    @Override
    public List<Favorite> getMyFavorites(int userId) throws SQLException {
        return favoriteDao.selectMyFavorites(userId);
    }

    /**
     * 获取用户在收藏中存在的分类
     *
     * @param userId
     * @return
     */
    @Override
    public List<FavoriteCategory> getMyFavoriteCategorysInFavorite(int userId) throws SQLException {
        return favoriteDao.selectMyLinkCategorysInFavorite(userId);
    }

    /**
     * 删除一个收藏
     *
     * @param favoriteId
     * @param userId
     * @return
     */
    @Override
    public int delFavorite(int favoriteId, int userId) throws SQLException {
        return favoriteDao.deleteFavorite(favoriteId,userId);
    }

    /**
     * 获取我的一个收藏
     *
     * @param favoriteId
     * @param userId
     * @return
     */
    @Override
    public Favorite getFavorite(int favoriteId, int userId) throws SQLException {
        return favoriteDao.getFavorite(favoriteId,userId);
    }
}
